package com.yuju.order.service.impl;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.yuju.roomStatus.model.RoomStatusModel;
import com.yuju.roomStatus.model.RoomTypeStatusModel;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.yuju.account.service.IAccountService;
import com.yuju.common.PageModel;
import com.yuju.common.Result;
import com.yuju.common.core.dao.IBaseDao;
import com.yuju.common.core.service.AbstractBaseService;
import com.yuju.enums.CheckinTypeEnum;
import com.yuju.enums.ReturnCodeEnum;
import com.yuju.enums.ReturnStatusEnum;
import com.yuju.enums.SeqCodeEnum;
import com.yuju.enums.StatusEnum;
import com.yuju.exception.BusinessException;
import com.yuju.group.enums.GuestInfoReturnCodeEnum;
import com.yuju.group.model.GuestInfoModel;
import com.yuju.group.model.OrderRelaModel;
import com.yuju.group.service.ICodeGenService;
import com.yuju.group.service.IGuestInfoService;
import com.yuju.group.service.IOrderRelaService;
import com.yuju.hotel.enums.CustomersEnum;
import com.yuju.hotel.enums.RoomReturnCodeEnum;
import com.yuju.hotel.model.RoomModel;
import com.yuju.hotel.service.IRoomService;
import com.yuju.log.model.LogBizRecordModel;
import com.yuju.log.service.ILogBizRecordService;
import com.yuju.model.account.AccountModel;
import com.yuju.order.dao.IRoomOrderDao;
import com.yuju.order.dao.entity.RoomOrder;
import com.yuju.order.enums.ChannelEnum;
import com.yuju.order.enums.OrderRelaReturnCodeEnum;
import com.yuju.order.enums.RentTypeEnum;
import com.yuju.order.enums.ReserveReturnCodeEnum;
import com.yuju.order.enums.ReserveStatusEnum;
import com.yuju.order.enums.RoomOrderGuestReturnCodeEnum;
import com.yuju.order.enums.RoomOrderReturnCodeEnum;
import com.yuju.order.enums.RoomOrderSettleStatusEnum;
import com.yuju.order.enums.RoomOrderStatusEnum;
import com.yuju.order.enums.SourceEnum;
import com.yuju.order.model.ReserveModel;
import com.yuju.order.model.RoomOrderGuestModel;
import com.yuju.order.model.RoomOrderModel;
import com.yuju.order.service.IReserverService;
import com.yuju.order.service.IRoomOrderGuestService;
import com.yuju.order.service.IRoomOrderService;
import com.yuju.roomStatus.service.IRoomStatusService;
import com.yuju.roomStatus.service.IRoomTypeStatusService;
import com.yuju.util.DateUtil;
import com.yuju.util.Utils;
/**
 * 
 * 类名：RoomOrderServiceImpl  <br />
 *
 * 功能：
 *
 * @author : sunyl <br />
 * @Date : 2017年11月24日 上午9:37:41  <br />
 * @version : 1.1 <br />
 */
@Service
public class RoomOrderServiceImpl extends AbstractBaseService<RoomOrderModel,RoomOrder,String> implements IRoomOrderService{
	@Autowired
	private IRoomOrderDao roomOrderDao;
	@Autowired
	private IRoomOrderGuestService roomOrderGuestService;
	@Autowired
	private IReserverService reserverService;
	@Autowired
	private IGuestInfoService guestInfoService;
	@Autowired
	private ICodeGenService codeGenService;
	@Autowired
	private IOrderRelaService orderRelaService;
	@Autowired
	private IRoomService roomService;
	@Autowired
	private IAccountService accountService;
	@Autowired
	private ILogBizRecordService logBizRecordService;
	
	@Autowired
	private IRoomTypeStatusService roomTypeStatusService;
	@Autowired
	private IRoomStatusService roomStatusService;
	
	@Override
	public IBaseDao<RoomOrderModel, RoomOrder, String> getDao() {
		return roomOrderDao;
	}
	@Override
	public int updateSelective(RoomOrderModel model) {
		int rows = 0;
		model.setGmtModified(new Date());
		rows = super.updateSelective(model);
		return rows;
	}
	@Override
	public int save(RoomOrderModel model) {
		// 保存数据
		model.setId(Utils.getUUID());
		model.setGmtCreate(new Date());
		model.setGmtModified(new Date());
		int rows = super.save(model);
		return rows;
	}
	/**
	 * 入住了的不能再入住，校验
	 * 功能：<br/>
	 *
	 * @author sunyl
	 * @Date 2018年1月25日 上午11:49:38 <br/>
	 */
	private void checkRoomorderGuest(String GuestId,String groupId,String hotelId){
		RoomOrderGuestModel roomOrderGuestModel = new RoomOrderGuestModel();
		roomOrderGuestModel.setCheckinStatus(RoomOrderStatusEnum.CHECKIN.getValue());
		roomOrderGuestModel.setRoomGuestId(GuestId);
		roomOrderGuestModel.setGroupId(groupId);
		roomOrderGuestModel.setHotelId(hotelId);
		RoomOrderGuestModel model = roomOrderGuestService.find(roomOrderGuestModel);
		if(model != null ){
			RoomModel roomModel  =  roomService.findById(model.getRoomId());
			if(roomModel == null){
				throw new BusinessException(RoomReturnCodeEnum.ROOM_QUERY_FAILURE.getCode(),
						RoomReturnCodeEnum.ROOM_QUERY_FAILURE.getDesc());
			}
			throw new BusinessException(RoomOrderGuestReturnCodeEnum.ROOM_ORDER_GUEST__VALID_CHECKIN_FAILURE.getCode(),
					RoomOrderGuestReturnCodeEnum.ROOM_ORDER_GUEST__VALID_CHECKIN_FAILURE.getDesc()+"。证件号："+model.getCertificateCode()+
					"房间号："+roomModel.getRoomCode());
		}
	}
	/**
	 * 保存订单
	 * 功能: <br/>
	 * 
	 * 重写：sunyl <br/>
	 * 
	 * @Date ：2017年12月12日 下午2:20:03<br/>
	 * 
	 * @param model 表单中的数据
	 * @param listRoomordermodel 房间列表
	 * @param listRoomOrderGuestModel 同来宾客的列表
	 * 1 生成关联订单
	 * 2 修改预订单
	 * 3 组织订单
	 * 4 主宾放入房间宾客中
	 * 5 预定订金改押金
	 * 6 保存房间宾客
	 * 7 保存订单
	 * 注意: a 订单和宾客订单信息存在交叉，订单中需要房间宾客的姓名拼接，
	 * 宾客房间中需要订单的orderId和roomId的一一对应，所以多出来来给三个临时集合
	 * 	b 返回值为订单的主键集合，方便前端打印
	 * listRoomOrderModelTemp，mapForKeyRoomIdValueOrderIdTemp，mapForKeyRoomIdValueOtherGuestNameTemp，
	 * @return <br/>
	 * @see com.yuju.order.service.IRoomOrderService#saveOrder(com.yuju.order.model.RoomOrderModel, java.util.List, java.util.List)
	 */
	@Override
	public List<String> saveOrder(RoomOrderModel model,List<RoomOrderModel> listRoomordermodel,
			List<RoomOrderModel> listRoomOrderGuestModel) {
		/*房间校验*/
		checkRoomStatus(model, listRoomordermodel);
		
		
		/*返回订单的列表*/
		List<String> listOrderId = new ArrayList<>();
		/*临时房间宾客的id*/
		List<String> listOrderGuestId = new ArrayList<>();
		//int rows = 0;
		/*1 生成关联订单*/
		String orderRelaId = null;
		if(listRoomordermodel.size() > 1){
			OrderRelaModel orderRelaModel = new OrderRelaModel();
			orderRelaId = Utils.getUUID();
			orderRelaModel.setGroupId(model.getGroupId());
			orderRelaModel.setHotelId(model.getHotelId());
			orderRelaModel.setId(orderRelaId);
			if(orderRelaService.saveExcepId(orderRelaModel)==0){
				throw new BusinessException
				(OrderRelaReturnCodeEnum.ROOM_ORDER_RELA_SAVE_FAILURE.getCode(), OrderRelaReturnCodeEnum.ROOM_ORDER_RELA_SAVE_FAILURE.getDesc());
			}
		}
		/*2 修改预订单*/
		if(model.getReserveId() != null){
			ReserveModel reserveModel = reserverService.findById(model.getReserveId());
			if(reserveModel == null){
				throw new BusinessException
				(RoomOrderReturnCodeEnum.ROOM_ORDER_UPDTAERESERVE_FAILURE.getCode(),RoomOrderReturnCodeEnum.ROOM_ORDER_UPDTAERESERVE_FAILURE.getDesc());
			}else{
				reserveModel.setReserveStatus(ReserveStatusEnum.ZAIZHU.getValue());
				reserveModel.setReserveStatusName(ReserveStatusEnum.ZAIZHU.getName());
				reserveModel.setGmtModified(new Date());
				if(reserverService.updateSelective(reserveModel)==0){
					throw new BusinessException
					(ReserveReturnCodeEnum.RESERVE_UPDATE_FAILURE.getCode(), ReserveReturnCodeEnum.RESERVE_UPDATE_FAILURE.getDesc());
				}
			}
		}
		/*3 组织订单*/
		/*临时存储组织后的订单，便于后期存储*/
		List<RoomOrderModel> listRoomOrderModelTemp = new ArrayList<>();
		Map<String,String> mapForKeyRoomIdValueOrderIdTemp = new HashMap<>();
		for(RoomOrderModel roomOrderModel : listRoomordermodel){
			String id = Utils.getUUID();
			listOrderId.add(id);
			roomOrderModel.setId(id);
			String orderNo = codeGenService.generate(model.getGroupId(), model.getHotelId(), model.getHotelCode(),SeqCodeEnum.ROOM_ORDER_CODE.getCode());
			if(orderNo == null){
				throw new BusinessException
				(ReturnCodeEnum.ORDER_NO_GEN_FALURE.getCode(), ReturnCodeEnum.ORDER_NO_GEN_FALURE.getDesc());
			}
			roomOrderModel.setRoomOrderNo(orderNo);
			roomOrderModel.setRelaId(orderRelaId);
			String guestinfoId = getGeustInfoId(roomOrderModel.getCertificateType(),
					roomOrderModel.getCertificateCode(), roomOrderModel.getName(),model.getMobile(),model.getGroupId(),model.getHotelId());
			listOrderGuestId.add(guestinfoId);
			roomOrderModel.setMainGuestId(guestinfoId);
			roomOrderModel.setReserveId(model.getReserveId());
			roomOrderModel.setClassId(model.getClassId());
			roomOrderModel.setHotelId(model.getHotelId());
			roomOrderModel.setGroupId(model.getGroupId());
			roomOrderModel.setDeposit(new BigDecimal(0));
			roomOrderModel.setBalance(new BigDecimal(0));
			roomOrderModel.setChannel(model.getChannel());
			if(model.getRentType() == RentTypeEnum.APRTMENT.getValue()){
					roomOrderModel.setRoomPrice(this.getDayPrice(new Date(), model.getCheckoutTime(),roomOrderModel.getMonthPrice()));
			}else{
				if(roomOrderModel.getRoomPrice() == null){
					throw new BusinessException(RoomOrderReturnCodeEnum.ORDER_ROOMPRICE_VALID_FAILURE.getCode(), 
							RoomOrderReturnCodeEnum.ORDER_ROOMPRICE_VALID_FAILURE.getDesc());
				}
			}
			roomOrderModel.setChannelName(ChannelEnum.getNameByValue(model.getChannel()));
			roomOrderModel.setUpdateUserId(model.getUpdateUserId());
			roomOrderModel.setCreateUserId(model.getCreateUserId());
			roomOrderModel.setRentType(model.getRentType());
			roomOrderModel.setSettleStatus(RoomOrderSettleStatusEnum.WEIJIE.getValue());
			roomOrderModel.setSettleStatusName((RoomOrderSettleStatusEnum.WEIJIE.getName()));
			
			roomOrderModel.setCheckinTime(new Date());
			roomOrderModel.setCheckoutTime(model.getCheckoutTime());
			roomOrderModel.setCustomId(model.getCustomId());
			roomOrderModel.setCustomType(model.getCustomType());
			roomOrderModel.setCustomTypeName(SourceEnum.getNameByValue(model.getCustomType()));
			roomOrderModel.setCheckinType(model.getCheckinType());
			roomOrderModel.setCheckinStandardId(model.getCheckinStandardId());
			roomOrderModel.setCheckinStandardName(model.getCheckinStandardName());
			roomOrderModel.setPriceSchemeId(model.getPriceSchemeId());
			roomOrderModel.setPriceSchemeName(model.getPriceSchemeName());
			roomOrderModel.setCheckinStatus(RoomOrderStatusEnum.CHECKIN.getValue());
			roomOrderModel.setCheckinStatusName(RoomOrderStatusEnum.CHECKIN.getName());
			roomOrderModel.setSaleId(model.getSaleId());
			
			roomOrderModel.setSaleName(model.getSaleName());
			
			roomOrderModel.setGmtCreate(new Date());
			roomOrderModel.setGmtModified(new Date());
			roomOrderModel.setCheckinTime(new Date());
			mapForKeyRoomIdValueOrderIdTemp.put(roomOrderModel.getRoomId(), id);
			listRoomOrderModelTemp.add(roomOrderModel);
			/* 4 主宾放入房间宾客中*/
			RoomOrderGuestModel roomOrderGuestModelInsert = new RoomOrderGuestModel();
			String roomOrderGuestId = Utils.getUUID();
			roomOrderGuestModelInsert.setId(roomOrderGuestId);
			roomOrderGuestModelInsert.setAccName(roomOrderModel.getName()+roomOrderModel.getRoomCode());
			roomOrderGuestModelInsert.setRoomGuestId(guestinfoId);
			roomOrderGuestModelInsert.setRoomOrderId(id);
			roomOrderGuestModelInsert.setBalance(new BigDecimal(0));
			roomOrderGuestModelInsert.setHotelId(roomOrderModel.getHotelId());
			roomOrderGuestModelInsert.setGroupId(roomOrderModel.getGroupId());
			roomOrderGuestModelInsert.setRoomId(roomOrderModel.getRoomId());
			roomOrderGuestModelInsert.setRemark(model.getRemark());
			if(roomOrderGuestService.saveExecptId(roomOrderGuestModelInsert) == 0){
				throw new BusinessException
				(RoomOrderReturnCodeEnum.ROOM_ORDER_SAVE_FAILURE.getCode(), RoomOrderReturnCodeEnum.ROOM_ORDER_SAVE_FAILURE.getDesc());
			}
		}
		/*6 保存房间宾客*/
		Map<String,Object> mapForKeyRoomIdValueOtherGuestNameTemp = new HashMap<>();
		if (Utils.isNotNull(listRoomOrderGuestModel) && !listRoomOrderGuestModel.isEmpty()) {
			for(RoomOrderModel roomOrderGuestModel : listRoomOrderGuestModel){
				RoomOrderGuestModel roomOrderGuestModelInsert = new RoomOrderGuestModel();
				roomOrderGuestModelInsert.setAccName(roomOrderGuestModel.getName()+roomOrderGuestModel.getRoomCode());
				String guestinfoId = getGeustInfoId(roomOrderGuestModel.getCertificateType(),
						roomOrderGuestModel.getCertificateCode(), roomOrderGuestModel.getName(),roomOrderGuestModel.getMobile(),model.getGroupId(),model.getHotelId());
				roomOrderGuestModelInsert.setRoomGuestId(guestinfoId);
				roomOrderGuestModelInsert.setRoomOrderId(mapForKeyRoomIdValueOrderIdTemp.get(roomOrderGuestModel.getRoomId()));
				roomOrderGuestModelInsert.setRoomId(roomOrderGuestModel.getRoomId());
				roomOrderGuestModelInsert.setBalance(new BigDecimal(0));
				roomOrderGuestModelInsert.setHotelId(model.getHotelId());
				roomOrderGuestModelInsert.setGroupId(model.getGroupId());
				roomOrderGuestModelInsert.setRemark(roomOrderGuestModel.getRemark());
				if(roomOrderGuestModel.getRemark()!=null){
					roomOrderGuestModelInsert.setRemark(roomOrderGuestModel.getRemark()+roomOrderGuestModel.getReasonRemark());
				}else{
					roomOrderGuestModelInsert.setRemark(roomOrderGuestModel.getReasonRemark());
				}
				if(roomOrderGuestService.save(roomOrderGuestModelInsert) == 0){
					throw new BusinessException
					(RoomOrderReturnCodeEnum.ROOM_ORDER_SAVE_FAILURE.getCode(), RoomOrderReturnCodeEnum.ROOM_ORDER_SAVE_FAILURE.getDesc());
				}
				String key = roomOrderGuestModel.getRoomId();
				Object value = mapForKeyRoomIdValueOtherGuestNameTemp.get(key);
				if(value == null){
					mapForKeyRoomIdValueOtherGuestNameTemp.put(key, roomOrderGuestModel.getName());
				}else{
					mapForKeyRoomIdValueOtherGuestNameTemp.put(roomOrderGuestModel.getRoomId(),
							value.toString() + "," + roomOrderGuestModel.getName());
				}
			}
		}
		/*7 保存订单*/
		for(RoomOrderModel roomOrderModel :listRoomOrderModelTemp ){
			roomOrderModel.setOtherGuestName
			(mapForKeyRoomIdValueOtherGuestNameTemp.get(roomOrderModel.getRoomId())!=null
			?mapForKeyRoomIdValueOtherGuestNameTemp.get(roomOrderModel.getRoomId()).toString():null);
			if(super.save(roomOrderModel) == 0){
				throw new BusinessException
				(RoomOrderReturnCodeEnum.ROOM_ORDER_SAVE_FAILURE.getCode(), 
						RoomOrderReturnCodeEnum.ROOM_ORDER_SAVE_FAILURE.getDesc());
			}
		}
		/* 5 预定订金改押金*/
		if(model.getReserveId()!= null){
			accountService.saveTransformAccount(model.getGroupId(), model.getHotelId(), model.getHotelCode(), model.getReserveId()
					, listOrderId.get(0),listOrderGuestId.get(0), model.getCreateUserId());
		}
		return listOrderId;
	}
	/*获取日均价*/
	private BigDecimal getDayPrice(Date checkinTime,Date checkoutTime,BigDecimal monthPrice){
		if(monthPrice == null){
			throw new BusinessException(RoomOrderReturnCodeEnum.ORDER_MONTHPRICE_VALID_FAILURE.getCode(),
					RoomOrderReturnCodeEnum.ORDER_MONTHPRICE_VALID_FAILURE.getDesc());
		}
		RoomTypeStatusModel roomTypeStatusModel = roomTypeStatusService.getApartPrice
				(checkinTime,checkoutTime,monthPrice);
		return roomTypeStatusModel.getDayPrice();
	}
	/**
	 * 校验房态
	 * 功能：<br/>
	 *
	 * @author sunyl
	 * @Date 2018年1月3日 下午6:34:23 <br/>
	 */
	private void checkRoomStatus(RoomOrderModel model,List<RoomOrderModel> listRoomordermodel
			){
		/*1 组织参数*/
		List<RoomStatusModel> roomStatusModelList = new ArrayList<>();
		for(RoomOrderModel roomOrderModel:listRoomordermodel){
			RoomStatusModel roomStatusModel = new RoomStatusModel();
			roomStatusModel.setRoomId(roomOrderModel.getRoomId());
			roomStatusModel.setReserveId(model.getReserveId());
			roomStatusModelList.add(roomStatusModel);
		}
		Date checkinTime = new Date();//变动的开始时间,直接入住时当天，换房和修改离期是checkinTime
		if(model.getCheckinTime()!=null){
			checkinTime = model.getCheckinTime();
		}
		/*2 校验*/
		List<RoomStatusModel> result = roomStatusService.verifyCheckinRoom(
						roomStatusModelList, checkinTime, model.getCheckoutTime());
		for(RoomStatusModel roomStatusModel:result){
			if(!roomStatusModel.getIsCheckinEnable()){
				throw new BusinessException(RoomOrderReturnCodeEnum.ROOM_ORDER_ROOM_VALID_FAILURE.getCode(),
						RoomOrderReturnCodeEnum.ROOM_ORDER_ROOM_VALID_FAILURE.getDesc());
			}
		}
	}
	/**
	 * 私有方法 获取客人信息的id
	 * 功能：<br/>
	 * 1 客人信息证件类型和证件号没有则存入
	 * 2 有姓名不同则存入
	 * 3 姓名相同则更新
	 *
	 * @author sunyl
	 * @Date 2017年12月6日 下午3:08:31 <br/>
	 */
	private String getGeustInfoId(Byte certificateType,String certificateCode,String name,String mobile,String groupId,String hotelId){
		String id = null;
		GuestInfoModel guestInfoModel = new GuestInfoModel();
		guestInfoModel.setCertificateType(certificateType);
		guestInfoModel.setCertificateCode(certificateCode);
		guestInfoModel.setGroupId(groupId);
		GuestInfoModel guestInfoModelFind = guestInfoService.find(guestInfoModel);
		if(guestInfoModelFind == null){
			id = Utils.getUUID();
			guestInfoModel.setId(id);
			guestInfoModel.setName(name);
			guestInfoModel.setMobile(mobile);
			if(guestInfoService.saveExceptId(guestInfoModel)==0){
				throw new BusinessException
				(GuestInfoReturnCodeEnum.GUESTINFO_SAVE_FAILURE.getCode(), GuestInfoReturnCodeEnum.GUESTINFO_SAVE_FAILURE.getDesc());
			};
			return id;
		}else{
			/**
			 * 入住了不能在入住
			 */
			checkRoomorderGuest(guestInfoModelFind.getId(),groupId,hotelId);
			if(guestInfoModelFind.getName().equals(name)){
				if(mobile != null){
					guestInfoModelFind.setMobile(mobile);
					guestInfoModelFind.setGmtModified(new Date());
					if(guestInfoService.updateSelective(guestInfoModelFind) == 0){
						throw new BusinessException
						(GuestInfoReturnCodeEnum.GUESTINFO_SAVE_FAILURE.getCode(), GuestInfoReturnCodeEnum.GUESTINFO_SAVE_FAILURE.getDesc());
					}
				}
				return guestInfoModelFind.getId();
			}else{
				id = Utils.getUUID();
				guestInfoModel.setName(name);
				guestInfoModel.setMobile(mobile);
				guestInfoModel.setId(id);
				if(guestInfoService.saveExceptId(guestInfoModel) == 0){
					throw new BusinessException
					(GuestInfoReturnCodeEnum.GUESTINFO_SAVE_FAILURE.getCode(), GuestInfoReturnCodeEnum.GUESTINFO_SAVE_FAILURE.getDesc());
				};
				return id;
			}
		}
	}
	/**
	 * 修改余额
	 * 功能: <br/>
	 * 
	 * 重写：sunyl <br/>
	 * 
	 * @Date ：2017年12月8日 下午2:14:56<br/>
	 * 
	 * @param roomOrderId
	 * @param money
	 * @return <br/>
	 * @see com.yuju.group.service.IRoomOrderService#updateRoomOrderForBalance(java.lang.String, java.math.BigDecimal)
	 */
	@Override
	public int updateRoomOrderForBalance(String roomOrderId, BigDecimal money) {
		int rows = 0;
		RoomOrderModel model = this.findById(roomOrderId);
		model.setId(roomOrderId);
		model.setBalance(model.getBalance().add(money));
		rows = this.updateSelective(model);
		return rows;
	}
	/**
	 * 哑房账单生成
	 * 功能: <br/>
	 * 
	 * 重写：sunyl <br/>
	 * 
	 * @Date ：2017年12月11日 下午6:34:16<br/>
	 * 
	 * @param groupId  集团id
	 * @param hotelId  酒店id
	 * @param empId  员工id
	 * @return <br/>
	 * @see com.yuju.group.service.IRoomOrderService#saveRoomOrderForDump(com.yuju.group.model.RoomOrderModel)
	 */
	@Override
	public String saveRoomOrderForDump(String roomOrderId,String groupId,String hotelId,String hotelCode,String empId,List<AccountModel> accountList) {
		/**
		 * 1 存在临客账单则更新 否则新增
		 */
		if(roomOrderId != null){
			RoomOrderModel model = super.findById(roomOrderId);
			model.setSettleStatus(RoomOrderSettleStatusEnum.YIFANJIE.getValue());
			model.setSettleStatusName(RoomOrderSettleStatusEnum.YIFANJIE.getName());
			model.setGmtModified(new Date());
			model.setCreateUserId(empId);
			model.setUpdateUserId(empId);
			if(0 == super.updateSelective(model)){
				throw new BusinessException
				(RoomOrderReturnCodeEnum.ROOM_ORDER_UPDATE_DUMP_FAILURE.getCode(),
						RoomOrderReturnCodeEnum.ROOM_ORDER_UPDATE_DUMP_FAILURE.getDesc());
			}
		}else{
			RoomOrderModel model = new RoomOrderModel();
			String orderNo = codeGenService.generate(groupId, hotelId, hotelCode, SeqCodeEnum.DUMB_ROOM_ORDER_CODE.getCode());
			if(orderNo == null){
				throw new BusinessException
				(ReturnCodeEnum.ORDER_NO_GEN_FALURE.getCode(), ReturnCodeEnum.ORDER_NO_GEN_FALURE.getDesc());
			}
			roomOrderId = Utils.getUUID();
			model.setId(roomOrderId);
			model.setRoomOrderNo(orderNo);
			// 入住状态为"临客"
			model.setCheckinStatus(RoomOrderStatusEnum.TEMPORARY.getValue());
			model.setCheckinStatusName(RoomOrderStatusEnum.TEMPORARY.getName());
			// 结账状态为"已结"
			model.setSettleStatus(RoomOrderSettleStatusEnum.YIJIE.getValue());
			model.setSettleStatusName(RoomOrderSettleStatusEnum.YIJIE.getName());
			
			Date date = new Date();
			model.setGmtCreate(date);
			model.setGmtModified(date);
			// 入住时间和离店时间，为该订单创建时间
			model.setCheckinTime(date);
			model.setCheckoutTime(date);
			
			model.setBalance(new BigDecimal(0));
			model.setGroupId(groupId);
			model.setHotelId(hotelId);
			model.setCreateUserId(empId);
			model.setUpdateUserId(empId);
			if(0 == super.save(model)){
				throw new BusinessException
				(RoomOrderReturnCodeEnum.ROOM_ORDER_SAVE_DUMP_FAILURE.getCode(),
						RoomOrderReturnCodeEnum.ROOM_ORDER_SAVE_DUMP_FAILURE.getDesc());
			}
		}
		/**
		 * 2 账务处理
		 */
		 int rows = accountService.saveDumpRoomAccount(accountList, roomOrderId);
		 if(rows==0){
			 throw new BusinessException(RoomOrderReturnCodeEnum.ROOM_ORDER_SAVE_DUMP_FAILURE.getCode(), 
					 RoomOrderReturnCodeEnum.ROOM_ORDER_SAVE_DUMP_FAILURE.getDesc());
		 }
		return roomOrderId;
	}
	/**
	 * 走结 
	 * 功能：<br/>
	 * 1 更改结算的状态为走结
	 * 2 入住状态 为离店
	 * @param roomOrderId roomorder主键
	 * @param goReason 走结原因
	 * @param 更改人 employee主键/  empid
 	 * @author sunyl
	 * @Date 2017年12月11日 下午6:12:29 <br/>
	 */
	@Override
	public int updateRoomOrderForZJ(String roomOrderId,String goReason,String empId) {
		/**
		 * 查询原订单校验状态
		 */
		RoomOrderModel find = super.findById(roomOrderId);
		if(find == null || find.getSettleStatus() != RoomOrderSettleStatusEnum.WEIJIE.getValue()){
			throw new BusinessException(RoomOrderReturnCodeEnum.ROOM_ORDER_UPDATE_FAILURE.getCode(),
					RoomOrderReturnCodeEnum.ROOM_ORDER_UPDATE_FAILURE.getCode());
		}
		if(find.getRoomManageStatus()==StatusEnum.TRUE.getValue()){
			throw new BusinessException(RoomOrderReturnCodeEnum.ROOM_QUIT_OUT_FAIL_FOR_ROOM_MANAGER.getCode(),
					RoomOrderReturnCodeEnum.ROOM_QUIT_OUT_FAIL_FOR_ROOM_MANAGER.getDesc());
		}
		/*储存*/
		RoomOrderModel model =new RoomOrderModel();
		model.setId(roomOrderId);
		model.setGoReason(goReason);
		model.setUpdateUserId(empId);
		model.setCheckinStatus(RoomOrderStatusEnum.CHECKOUT.getValue());
		model.setCheckinStatusName(RoomOrderStatusEnum.CHECKOUT.getName());
		model.setSettleStatus(RoomOrderSettleStatusEnum.ZOUJIE.getValue());
		model.setSettleStatusName(RoomOrderSettleStatusEnum.ZOUJIE.getName());
		model.setCheckoutTime(new Date());
		return this.updateSelective(model);
	}
	/**
	 * 结算的账单修改
	 * 功能：<br/>
	 *  @param roomOrderId roomorder主键
	 *  @param 更改人 employee主键/  empid
	 * 1 更改结算的状态为已结算
	 * 2 入住状态为离店
	 * @author sunyl
	 * @Date 2017年12月11日 下午6:12:29 <br/>
	 */
	@Override
	public int updateRoomOrderForJS(String roomOrderId,String empId) {
		RoomOrderModel find = super.findById(roomOrderId);
		if(find.getRoomManageStatus()==StatusEnum.TRUE.getValue()){
			throw new BusinessException(RoomOrderReturnCodeEnum.ROOM_QUIT_OUT_FAIL_FOR_ROOM_MANAGER.getCode(),
					RoomOrderReturnCodeEnum.ROOM_QUIT_OUT_FAIL_FOR_ROOM_MANAGER.getDesc());
		}
		if(find.getRoomManageStatus()==StatusEnum.TRUE.getValue()){
			throw new BusinessException(RoomOrderReturnCodeEnum.ROOM_QUIT_OUT_FAIL_FOR_ROOM_MANAGER.getCode(),
					RoomOrderReturnCodeEnum.ROOM_QUIT_OUT_FAIL_FOR_ROOM_MANAGER.getDesc());
		}
		RoomOrderModel model = new RoomOrderModel();
		model.setId(roomOrderId);
		model.setUpdateUserId(empId);
		model.setCheckinStatus(RoomOrderStatusEnum.CHECKOUT.getValue());
		model.setCheckinStatusName(RoomOrderStatusEnum.CHECKOUT.getName());
		model.setSettleStatus(RoomOrderSettleStatusEnum.YIJIE.getValue());
		model.setSettleStatusName(RoomOrderSettleStatusEnum.YIJIE.getName());
		int rows = this.updateSelective(model);
		return rows;
	}
	/**
	 * 退出联防
	 * 功能: <br/>
	 * 
	 * 重写：xuehj <br/>
	 * 
	 * @Date ：2017年12月15日 下午3:26:54<br/>
	 * 
	 * @param roomOrdeIdList
	 * @return <br/>
	 * @see com.yuju.order.service.IRoomOrderService#quitOrderRela(java.util.List)
	 */
	@Override
	public int quitOrderRela(List<String> roomOrdeIdList,String relaId) {
		RoomOrderModel roomOrderModel = new RoomOrderModel();
		roomOrderModel.setRelaId(relaId);
		List<RoomOrderModel> roomOrderList = super.list(roomOrderModel);
		if(roomOrderList == null){
			throw new BusinessException(RoomOrderReturnCodeEnum.ROOM_ORDER_QUERY_FAILURE.getCode(), 
					RoomOrderReturnCodeEnum.ROOM_ORDER_QUERY_FAILURE.getDesc());
		}
		if(roomOrderList.size() == roomOrdeIdList.size()+1){
			dissolveOrderRela(relaId);
		}else{
			for(String id : roomOrdeIdList){
				RoomOrderModel model = this.findById(id);
				if(model == null){
					throw new BusinessException(RoomOrderReturnCodeEnum.ROOM_ORDER_QUERY_FAILURE.getCode(),
							RoomOrderReturnCodeEnum.ROOM_ORDER_QUERY_FAILURE.getDesc());
				}
				model.setId(id);
				model.setRelaId(null);
				model.setGmtModified(new Date());
				if(0 == super.update(model)){
					throw new BusinessException(RoomOrderReturnCodeEnum.ROOM_ORDER_QUERY_RELA_FAILURE.getCode(),
							RoomOrderReturnCodeEnum.ROOM_ORDER_QUERY_RELA_FAILURE.getDesc());
				}
			}
			
		}
		return 1;
	}
	/**
	 * 加入联房
	 * 1查询联房Id 有则直接设置  无则插入联房单，跟新订单表
	 * 2插入联房
	 * 功能：<br/>
	 *
	 * @author sunyl
	 * @Date 2017年12月15日 下午3:43:13 <br/>
	 */
	@Override
	public int joinOrderRela(String roomOrderId,List<String> roomOrdeIdList,String groupId,String hotelId) {
		String relaId ;
		/*1查询联房Id*/
		RoomOrderModel roomOrderModel = super.findById(roomOrderId);
		if(roomOrderModel ==null ){
			throw new BusinessException
			(RoomOrderReturnCodeEnum.ROOM_ORDER_QUERY_FAILURE.getCode(),
					RoomOrderReturnCodeEnum.ROOM_ORDER_QUERY_FAILURE.getDesc());
		}
		if(roomOrderModel.getRelaId() == null){
			OrderRelaModel model = new OrderRelaModel();
			relaId = Utils.getUUID();
			model.setId(relaId);
			model.setGroupId(groupId);
			model.setHotelId(hotelId);
			/*a插入联防*/
			if(0 == orderRelaService.saveExcepId(model)){
				throw new BusinessException
				(OrderRelaReturnCodeEnum.ROOM_ORDER_RELA_SAVE_FAILURE.getCode(), 
						OrderRelaReturnCodeEnum.ROOM_ORDER_RELA_SAVE_FAILURE.getDesc());
			}
			/*b更新订单*/
			roomOrderModel.setRelaId(relaId);
			if(0 == super.updateSelective(roomOrderModel)){
				throw new BusinessException
				(RoomOrderReturnCodeEnum.ROOM_ORDER_UPDATE_FAILURE.getCode(), 
						RoomOrderReturnCodeEnum.ROOM_ORDER_UPDATE_FAILURE.getDesc());
			}
			
		}else{
			relaId =  roomOrderModel.getRelaId();
		}
		/*2插入联房*/
		int  rows = 0;
		for(String id : roomOrdeIdList){
			RoomOrderModel model = new RoomOrderModel();
			model.setId(id);
			model.setRelaId(relaId);
			model.setGmtModified(new Date());
			rows = rows + super.updateSelective(model);
		}
		return rows;
	}
	/**
	 * 解散联防
	 * 功能: <br/>
	 * 
	 * 重写：xuehj <br/>
	 * 
	 * @Date ：2017年12月15日 下午4:03:22<br/>
	 * 
	 * @param relaId
	 * @param roomOrderIdList
	 * @return <br/>
	 * @see com.yuju.order.service.IRoomOrderService#dissolveOrderRela(java.lang.String, java.util.List)
	 */
	@Override
	public List<RoomOrderModel> dissolveOrderRela(String relaId) {
		int rows = 0;
		RoomOrderModel roomOrderModel = new RoomOrderModel();
		roomOrderModel.setRelaId(relaId);
		List<RoomOrderModel> finds = super.list(roomOrderModel);
		for(RoomOrderModel find:finds){
			find.setRelaId(null);
			find.setGmtModified(new Date());
			if(0 == super.update(find)){
				throw new BusinessException
				(RoomOrderReturnCodeEnum.ROOM_ORDER_UPDATE_FAILURE.getCode(), 
						RoomOrderReturnCodeEnum.ROOM_ORDER_UPDATE_FAILURE.getDesc());
			}
		}
		OrderRelaModel orderRelaModel = orderRelaService.findById(relaId);
		orderRelaModel.setGmtModified(new Date());
		orderRelaModel.setIsDeleted(StatusEnum.TRUE.getValue());
		rows = orderRelaService.updateSelective(orderRelaModel);
		if(rows == 0){
			throw new BusinessException(RoomOrderReturnCodeEnum.ROOM_ORDER_ROOM_DISSOLVE_FAILURE.getCode(),
					RoomOrderReturnCodeEnum.ROOM_ORDER_ROOM_DISSOLVE_FAILURE.getDesc());
		}
		return finds;
	}

	/**
	 * 修改押金
	 * 功能: <br/>
	 * 
	 * 重写：sunyl <br/>
	 * 
	 * @Date ：2017年12月8日 下午2:15:13<br/>
	 * 
	 * @param roomOrderId
	 * @param money
	 * @return <br/>
	 * @see com.yuju.group.service.IRoomOrderService#updateRoomOrderForDeposit(java.lang.String, java.math.BigDecimal)
	 */
	@Override
	public int updateRoomOrderForDeposit(String roomOrderId, BigDecimal money) {
		int rows = 0;
		RoomOrderModel model = this.findById(roomOrderId);
		model.setId(roomOrderId);
		model.setDeposit(model.getDeposit().add(money));
		rows = this.updateSelective(model);
		return rows;
	}

	/**
	 * 更改离期
	 * 功能：<br/>
	 *
	 * @author sunyl
	 * @Date 2017年12月9日 下午4:26:51 <br/>
	 */
	@Override
	public RoomOrderModel updateForCheckoutTime(String id,Date checkoutTime) {
		/*1房态校验*/
		/*a 组织参数*/
		/*RoomOrderModel roomOrderModel = super.findById(id);
		RoomOrderGuestModel roomOrderGuestModel = new RoomOrderGuestModel();
		roomOrderGuestModel.setRoomOrderId(id);
		List<RoomOrderModel> roomOrderGuestModelList = new ArrayList<>();
		b 校验
		roomOrderModel.setCheckoutTime(checkoutTime);
		roomOrderModel.setCheckinTime(roomOrderModel.getCheckoutTime());
		roomOrderGuestModelList.add(roomOrderModel);*/
		//checkRoomStatus(roomOrderModel, roomOrderGuestModelList);
		/*2 修改时间*/
		int rows = 0;
		RoomOrderModel model = new RoomOrderModel();
		RoomOrderModel find = super.findById(id);
		model.setId(id);
		model.setCheckoutTime(checkoutTime);
		model.setGmtModified(new Date());
		rows = this.updateSelective(model);
		if(rows == 0){
			throw new BusinessException(RoomOrderReturnCodeEnum.ROOM_ORDER_UPDATE_CHECKOURT_FAILURE.getCode(),
					RoomOrderReturnCodeEnum.ROOM_ORDER_UPDATE_CHECKOURT_FAILURE.getDesc());
		}
		return find;
	}
	@Override
	public RoomOrderModel updateForSource(RoomOrderModel model) {
		RoomOrderModel roomOrderModel = new RoomOrderModel();
		RoomOrderModel find = super.findById(model.getId());
		if(find==null){
			throw new BusinessException(RoomOrderReturnCodeEnum.ROOM_ORDER_QUERY_NO_FAILURE.getCode(),
					RoomOrderReturnCodeEnum.ROOM_ORDER_QUERY_NO_FAILURE.getDesc());
		}
		roomOrderModel.setId(find.getId());
		roomOrderModel.setCustomId(model.getCustomId());
		roomOrderModel.setCustomType(model.getCustomType());
		roomOrderModel.setCustomTypeName(SourceEnum.getNameByValue(model.getCustomType()));
		roomOrderModel.setPriceSchemeId(model.getPriceSchemeId());
		roomOrderModel.setPriceSchemeName(model.getPriceSchemeName());
		roomOrderModel.setCheckinStandardId(model.getCheckinStandardId());
		roomOrderModel.setCheckinStandardName(model.getCheckinStandardName());
		roomOrderModel.setCheckinType(model.getCheckinType());
		roomOrderModel.setRoomPrice(model.getRoomPrice());
		if(model.getMonthPrice() != null){
			RoomTypeStatusModel roomTypeStatusModel = roomTypeStatusService.getApartPrice
					(find.getCheckinTime(),find.getCheckoutTime(),model.getMonthPrice());
			roomOrderModel.setRoomPrice(roomTypeStatusModel.getDayPrice());
			roomOrderModel.setMonthPrice(model.getMonthPrice());
		}
		if(this.updateSelective(roomOrderModel) == 0 ){
			throw new BusinessException(RoomOrderReturnCodeEnum.ROOM_ORDER_UPDATE_FAILURE.getCode(), 
					RoomOrderReturnCodeEnum.ROOM_ORDER_UPDATE_FAILURE.getDesc());
		}
		return find;
	}
	/**
	 * 获取关联订单
	 * 功能：<br/>
	 * 
	 * @author sunyl
	 * @Date 2017年12月9日 下午5:00:34 <br/>
	 */
	@Override
	public List<RoomOrderModel> getOrderRela(String id) {
		/*1 获取订单*/
		RoomOrderModel find  = super.findById(id);
		if(find == null){
			throw new BusinessException(RoomOrderReturnCodeEnum.ROOM_ORDER_QUERY_FAILURE.getCode(),
					RoomOrderReturnCodeEnum.ROOM_ORDER_QUERY_FAILURE.getDesc());
		}
		/*2 获取订单关联*/
		String relaId = find.getRelaId();
		if(relaId == null){
			throw new BusinessException(RoomOrderReturnCodeEnum.ROOM_ORDER_QUERY_RELA_FAILURE.getCode(),
					RoomOrderReturnCodeEnum.ROOM_ORDER_QUERY_RELA_FAILURE.getDesc());
		}
		/*3 获取订单关联订单*/
		RoomOrderModel roomOrderModelParam = new RoomOrderModel(); 
		roomOrderModelParam.setRelaId(relaId);
		roomOrderModelParam.setGroupId(find.getGroupId());
		roomOrderModelParam.setHotelId(find.getHotelId());
		return super.list(roomOrderModelParam);
	}
	
	/**
	 * 获取关联订单通过订单id
	 * 功能：<br/>
	 * 
	 * @author sunyl
	 * @Date 2017年12月9日 下午5:00:34 <br/>
	 */
	@Override
	public List<RoomOrderModel> getOrderRelaByOrderId(String id) {
		/*1 获取订单*/
		RoomOrderModel find  = super.findById(id);
		if(find == null){
			throw new BusinessException(RoomOrderReturnCodeEnum.ROOM_ORDER_QUERY_FAILURE.getCode(),
					RoomOrderReturnCodeEnum.ROOM_ORDER_QUERY_FAILURE.getDesc());
		}
		/*2 获取订单关联*/
		String relaId = find.getRelaId();
		if(relaId == null){
			List<RoomOrderModel> list = new ArrayList<>();
			list.add(find);
			return list;
		}
		/*3 获取订单关联订单*/
		RoomOrderModel roomOrderModelParam = new RoomOrderModel(); 
		roomOrderModelParam.setRelaId(relaId);
		roomOrderModelParam.setGroupId(find.getGroupId());
		roomOrderModelParam.setHotelId(find.getHotelId());
		List<RoomOrderModel> finds = super.list(roomOrderModelParam);
		List<String> roomorderIdList = new ArrayList<>();
		for(RoomOrderModel modelT:finds){
			roomorderIdList.add(modelT.getId());
		}
		if(finds.size() > 1){
			RoomOrderModel orderRela = new RoomOrderModel();
			orderRela.setName("联房订单");
			orderRela.setCheckinTime(null);
			orderRela.setId(roomorderIdList.toString());
			finds.add(0,orderRela);
		}
		return finds;
	}
	/**
	 * 改价
	 * 功能：<br/>
	 *
	 * @author sunyl
	 * @Date 2017年12月9日 下午4:26:51 <br/>
	 */
	@Override
	public RoomOrderModel updateForRoomPrice(String id,BigDecimal roomPrice,BigDecimal monthPrice,String reasonRemark) {
		int rows = 0;
		RoomOrderModel model = new RoomOrderModel();
		RoomOrderModel find = super.findById(id);
		if(find == null){
			throw new BusinessException
			(RoomOrderReturnCodeEnum.ROOM_ORDER_QUERY_FAILURE.getCode(), 
					RoomOrderReturnCodeEnum.ROOM_ORDER_QUERY_FAILURE.getDesc());
		}
		model.setId(find.getId());
		model.setRoomPrice(roomPrice);
		model.setMonthPrice(monthPrice);
		model.setGmtModified(new Date());
		/*if(model.getRemark()==null){
			model.setRemark(reasonRemark);
		}else{
			model.setRemark(model.getRemark()+","+reasonRemark);
		}*/
		if(monthPrice != null ){
			model.setRoomPrice(this.getDayPrice(find.getCheckinTime(), find.getCheckoutTime(), monthPrice));
		}
		rows = this.updateSelective(model);
		if(rows ==0 ){
			throw new BusinessException(RoomOrderReturnCodeEnum.ROOM_ORDER_UPDATE_PRICE_FAILURE.getCode(),
					RoomOrderReturnCodeEnum.ROOM_ORDER_UPDATE_PRICE_FAILURE.getDesc());
		}
		return find;
	}
	/**
	 * 换房
	 * 功能: <br/>
	 * 
	 * 重写：sunyl <br/>
	 * 
	 * @Date ：2017年12月11日 下午3:49:42<br/>
	 *  1修改掉订单的房价和房间信息
	 *  2 把原房间修改为脏房
	 * @param id
	 * @param roomId
	 * @param oldRoomId
	 * @param roomCode
	 * @param roomPrice
	 * @return <br/>
	 * @see com.yuju.group.service.IRoomOrderService#updateForRoom(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.math.BigDecimal)
	 */
	@Override
	public RoomOrderModel updateForRoom(RoomOrderModel roomOrdermodel){
		
		RoomOrderModel find = super.findById(roomOrdermodel.getId());
		RoomOrderModel model = new RoomOrderModel();
		if(find == null){
			throw new BusinessException
			(RoomOrderReturnCodeEnum.ROOM_ORDER_QUERY_FAILURE.getCode(), 
					RoomOrderReturnCodeEnum.ROOM_ORDER_QUERY_FAILURE.getDesc());
		}
		model.setId(find.getId());
		String oldRoomId = find.getRoomId();
		/*校验房态*/
		model.setRoomId(roomOrdermodel.getRoomId());
		List<RoomOrderModel> listRoomordermodel = new ArrayList<>();
		listRoomordermodel.add(model);
		checkRoomStatus(model, listRoomordermodel);
		/*1修改掉订单的房价和房间信息*/
		model.setRoomCode(roomOrdermodel.getRoomCode());
		model.setRoomTypeId(roomOrdermodel.getRoomTypeId());
		model.setRoomTypeName(roomOrdermodel.getRoomTypeName());
		model.setPriceSchemeId(roomOrdermodel.getPriceSchemeId());
		model.setPriceSchemeName(roomOrdermodel.getPriceSchemeName());
		model.setGoReason(roomOrdermodel.getGoReason());
		model.setRoomPrice(roomOrdermodel.getRoomPrice());
		if(roomOrdermodel.getMonthPrice() != null ){
			RoomTypeStatusModel roomTypeStatusModel = roomTypeStatusService.getApartPrice
					(find.getCheckinTime(),find.getCheckoutTime(),roomOrdermodel.getMonthPrice());
			model.setRoomPrice(roomTypeStatusModel.getDayPrice());
		}
		if(0 == this.updateSelective(model)){
			throw new BusinessException
			(RoomOrderReturnCodeEnum.ROOM_ORDER_UPDATE_ROOM_FAILURE.getCode(), (RoomOrderReturnCodeEnum.ROOM_ORDER_UPDATE_ROOM_FAILURE.getDesc()));
		}
		/*2 把原房间修改为脏房*/
		RoomModel roomModel = new RoomModel();
		roomModel.setId(oldRoomId);
		roomModel.setIsDirty((byte)1);
		
		if(0 == roomService.updateSelective(roomModel)){
			throw new BusinessException(RoomReturnCodeEnum.ROOM_UPDATE_FAILURE.getCode(),RoomReturnCodeEnum.ROOM_UPDATE_FAILURE.getDesc());
		}
		return find;
	}
	
	/**
	 * 
	 * 功能:定時任務，预离未离 自动延住一天 
	 * 
	 * 重写：zhousc <br/>
	 * 
	 * @Date ：2017年12月18日 下午4:37:03<br/>
	 *  <br/>
	 * @see com.yuju.order.service.IRoomOrderService#updateCheckoutDate()
	 */
	@Override
	public void updateCheckoutDate() {
		roomOrderDao.updateCheckoutDate();
	}
	/**
	 * 订单查询
	 * 功能：<br/>
	 *
	 * @author sunyl
	 * @Date 2017年12月21日 上午11:59:54 <br/>
	 */
	@Override
	public PageModel listForSearch(RoomOrderModel model, Integer currentPage, Integer rows,Integer orderType, Integer outDay) {
		RoomOrderModel queryOrder = getObjectFromQuery(model, orderType, outDay);
		PageModel pageModel = super.pageList(queryOrder, currentPage, rows);
        return pageModel;
	}
	/**
	 * 订单查询
	 * 功能：<br/>
	 *
	 * @author sunyl
	 * @Date 2017年12月21日 上午11:59:54 <br/>
	 */
	@Override
	public List<LogBizRecordModel>  listForLog(LogBizRecordModel model, Integer orderType, Integer outDay) {
		LogBizRecordModel queryOrder = getObjectFromQuery(model, orderType, outDay);
		List<LogBizRecordModel> list = logBizRecordService.list(queryOrder);
		if(list != null  && list.size()>0){
			formatLogRecordByDetail(list);
		}
		return list;
	}
	/**
	 *
	 * 功能: <br/>
	 * sunyl
	 * 重写：xuehj <br/>
	 *  从模板中取代代码
	 * @Date ：2018年2月2日 上午11:12:58<br/>
	 * 
	 * @param list <br/>
	 * @see com.yuju.order.service.IRoomOrderService#formatLogRecordByDetail(java.util.List)
	 */
	@Override
	public void formatLogRecordByDetail(List<LogBizRecordModel> list){
		for(LogBizRecordModel item :list ){
			String str = item.getBizDetail();
			item.setNewRoomCode(getNewRoomCode(str));
			item.setOldRoomCode(getOldRoomCode(str));
			item.setNewRoomPrice(getNewRoomPrice(str));
			item.setOldRoomPrice(getOldRoomPrice(str));
			item.setNewPricePlan(getNewPricePlan(str));
			item.setOldPricePlan(getOldPricePlan(str));
		}
	}
	private String getNewRoomCode(String str){
		String s1 = StringUtils.substringAfterLast(str, "新房间号：");
		String s = StringUtils.substringBefore(s1, "，");
		return s;
	}
	private String getOldRoomCode(String str){
		String s1 = StringUtils.substringAfterLast(str, "原房间号：");
		String s = StringUtils.substringBefore(s1, "，");
		return s;
	}
	private String getNewRoomPrice(String str){
		String s1 = StringUtils.substringAfterLast(str, "新房价：");
		String s = StringUtils.substringBefore(s1, "，");
		return s;
	}
	private String getOldRoomPrice(String str){
		String s1 = StringUtils.substringAfterLast(str, "原房价：");
		String s = StringUtils.substringBefore(s1, "，");
		return s;
	}
	private String getNewPricePlan(String str){
		String s1 = StringUtils.substringAfterLast(str, "新价格方案：");
		String s = StringUtils.substringBefore(s1, "，");
		return s;
	}
	private String getOldPricePlan(String str){
		String s1 = StringUtils.substringAfterLast(str, "原价格方案：");
		String s = StringUtils.substringBefore(s1, "，");
		return s;
	}
	@Override
	public PageModel listForSearchWithAccounts(RoomOrderModel model, Integer currentPage, Integer rows,Integer orderType, Integer outDay) {
		RoomOrderModel queryOrder = getObjectFromQuery(model, orderType, outDay);
		PageModel pageModel = super.pageList(queryOrder, currentPage, rows);
		if(pageModel.getRows() !=null ){
			@SuppressWarnings("unchecked")
			List<RoomOrderModel> roomOrderModelList =(List<RoomOrderModel>) pageModel.getRows();
			for(RoomOrderModel  roomOrderModel :roomOrderModelList){
				AccountModel accountModel = new AccountModel();
				accountModel.setRoomOrderId(roomOrderModel.getId());
				roomOrderModel.setAccountList(accountService.list(accountModel));
			}
		}
		return pageModel;
	}
	
	/**
	 * 处理订单类型和离店日期的查询条件
	 * 功能：<br/>
	 *
	 * @author sunyl
	 * @Date 2017年12月21日 上午11:31:36 <br/>
	 */
	public RoomOrderModel getObjectFromQuery(RoomOrderModel queryOrder, Integer orderType, Integer outDay) {

        if (orderType != null) {
            switch (orderType) {
                //在住订单
                case 1:
                    queryOrder.setCheckinStatus(RoomOrderStatusEnum.CHECKIN.getValue());
                    break;
                //今日预离
                case 2:
                    queryOrder.setCheckoutDay(new Date());
                    queryOrder.setCheckinStatus(RoomOrderStatusEnum.CHECKIN.getValue());
                    break;
                //今日到今日离
                case 3:
                    queryOrder.setCheckinStatus(RoomOrderStatusEnum.CHECKIN.getValue());
                    queryOrder.setCheckinDay(new Date());
                    queryOrder.setCheckoutDay(new Date());
                    break;
                //历史订单
                case 4:
                    queryOrder.setCheckinStatus(RoomOrderStatusEnum.CHECKOUT.getValue());
                    break;
                //哑房订单
                case 5:
                    queryOrder.setCheckinStatus(RoomOrderStatusEnum.TEMPORARY.getValue());
                    break;
                //走结订单
                case 6:
                    queryOrder.setSettleStatus(RoomOrderSettleStatusEnum.ZOUJIE.getValue());
                    break;
                //反结订单
                case 7:
                    queryOrder.setSettleStatus(RoomOrderSettleStatusEnum.YIFANJIE.getValue());
                    break;
                default:
                    break;
            }
        }

        if (outDay != null) {
            switch (outDay) {
                //当天
                case 1:
                    queryOrder.setCheckinStatus(RoomOrderStatusEnum.CHECKOUT.getValue());
//                    queryOrder.setBeginCheckoutDay(0);
//                    queryOrder.setEndCheckoutDay(0);
                    queryOrder.setCheckoutDay(new Date());
                    break;
                //昨天
                case 2:
                    queryOrder.setCheckinStatus(RoomOrderStatusEnum.CHECKOUT.getValue());
                    queryOrder.setBeginCheckoutDay(-1);
                    queryOrder.setEndCheckoutDay(-1);
                    break;
                //最近三天
                case 3:
                    queryOrder.setCheckinStatus(RoomOrderStatusEnum.CHECKOUT.getValue());
                    queryOrder.setBeginCheckoutDay(-2);
                    queryOrder.setEndCheckoutDay(0);
                    break;
                //最近7天
                case 4:
                    queryOrder.setCheckinStatus(RoomOrderStatusEnum.CHECKOUT.getValue());
                    queryOrder.setBeginCheckoutDay(-6);
                    queryOrder.setEndCheckoutDay(0);
                    break;
                //本月
                case 5:
                    queryOrder.setCheckinStatus(RoomOrderStatusEnum.CHECKOUT.getValue());
                    queryOrder.setBeginCheckoutDay(getMonthBeginToNow(0));
                    queryOrder.setEndCheckoutDay(getMonthEndToNow(0));
                    break;
                //上月
                case 6:
                    queryOrder.setCheckinStatus(RoomOrderStatusEnum.CHECKOUT.getValue());
                    queryOrder.setBeginCheckoutDay(getMonthBeginToNow(-1));
                    queryOrder.setEndCheckoutDay(getMonthEndToNow(-1));
                    break;
                default:
                    break;
            }
        }
        return  queryOrder;
    }
	public LogBizRecordModel getObjectFromQuery(LogBizRecordModel queryOrder, Integer orderType, Integer outDay) {
		
		if (orderType != null) {
			switch (orderType) {
			//在住订单
			case 1:
				queryOrder.setCheckinStatus(RoomOrderStatusEnum.CHECKIN.getValue());
				break;
				//今日预离
			case 2:
				queryOrder.setCheckoutDay(new Date());
				queryOrder.setCheckinStatus(RoomOrderStatusEnum.CHECKIN.getValue());
				break;
				//今日到今日离
			case 3:
				queryOrder.setCheckinStatus(RoomOrderStatusEnum.CHECKIN.getValue());
				queryOrder.setCheckinDay(new Date());
				queryOrder.setCheckoutDay(new Date());
				break;
				//历史订单
			case 4:
				queryOrder.setCheckinStatus(RoomOrderStatusEnum.CHECKOUT.getValue());
				break;
				//哑房订单
			case 5:
				queryOrder.setCheckinStatus(RoomOrderStatusEnum.TEMPORARY.getValue());
				break;
				//走结订单
			case 6:
				queryOrder.setSettleStatus(RoomOrderSettleStatusEnum.ZOUJIE.getValue());
				break;
				//反结订单
			case 7:
				queryOrder.setSettleStatus(RoomOrderSettleStatusEnum.YIFANJIE.getValue());
				break;
			default:
				break;
			}
		}
		
		if (outDay != null) {
			switch (outDay) {
			//当天
			case 1:
				queryOrder.setCheckinStatus(RoomOrderStatusEnum.CHECKOUT.getValue());
//                    queryOrder.setBeginCheckoutDay(0);
//                    queryOrder.setEndCheckoutDay(0);
				queryOrder.setCheckoutDay(new Date());
				break;
				//昨天
			case 2:
				queryOrder.setCheckinStatus(RoomOrderStatusEnum.CHECKOUT.getValue());
				queryOrder.setBeginCheckoutDay(-1);
				queryOrder.setEndCheckoutDay(-1);
				break;
				//最近三天
			case 3:
				queryOrder.setCheckinStatus(RoomOrderStatusEnum.CHECKOUT.getValue());
				queryOrder.setBeginCheckoutDay(-2);
				queryOrder.setEndCheckoutDay(0);
				break;
				//最近7天
			case 4:
				queryOrder.setCheckinStatus(RoomOrderStatusEnum.CHECKOUT.getValue());
				queryOrder.setBeginCheckoutDay(-6);
				queryOrder.setEndCheckoutDay(0);
				break;
				//本月
			case 5:
				queryOrder.setCheckinStatus(RoomOrderStatusEnum.CHECKOUT.getValue());
				queryOrder.setBeginCheckoutDay(getMonthBeginToNow(0));
				queryOrder.setEndCheckoutDay(getMonthEndToNow(0));
				break;
				//上月
			case 6:
				queryOrder.setCheckinStatus(RoomOrderStatusEnum.CHECKOUT.getValue());
				queryOrder.setBeginCheckoutDay(getMonthBeginToNow(-1));
				queryOrder.setEndCheckoutDay(getMonthEndToNow(-1));
				break;
			default:
				break;
			}
		}
		return  queryOrder;
	}
	//某月第一天和当前的天数差
	private int getMonthBeginToNow(int month) {
        Calendar cale = null;
        cale = Calendar.getInstance();
        cale.add(Calendar.MONTH, month);
        cale.set(Calendar.DAY_OF_MONTH, 1);
        Date fromTime = cale.getTime();
        cale.setTime(new Date());
        Date toTime = cale.getTime();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return (int)(DateUtil.getDiffDay(sdf.format(fromTime),sdf.format(toTime)));
    }

    //某月第一天和当前的天数差
    private int getMonthEndToNow(int month) {
        Calendar cale = null;
        cale = Calendar.getInstance();
        cale.add(Calendar.MONTH, month + 1);
        cale.set(Calendar.DAY_OF_MONTH, 0);
        Date fromTime = cale.getTime();
        cale.setTime(new Date());
        Date toTime = cale.getTime();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return (int)(DateUtil.getDiffDay(sdf.format(fromTime),sdf.format(toTime)));
    }
    /**
     * 重写获取订单客人信息
     * 功能: <br/>
     * 
     * 重写：xuehj <br/>
     * 
     * @Date ：2017年12月21日 下午6:10:22<br/>
     * 
     * @param model
     * @return <br/>
     * @see com.yuju.common.core.service.AbstractBaseService#find(java.lang.Object)
     */
    @Override
	public RoomOrderModel find(RoomOrderModel model) {
		model = super.find(model);
		if(model !=null && model.getId()!=null){
			Map<String,Object> AccountForMoneyMap = accountService.getDetailByOrderId(model.getId());
			model.setTotalBill(AccountForMoneyMap.get("ysSum"));
			model.setSettlementTotal(AccountForMoneyMap.get("ssSum"));
			model.setPreReceivables(AccountForMoneyMap.get("yusSum"));
		}
		return model;
	}
    /**
     * 新增同来宾客
     * 功能：<br/>
     *
     * @author sunyl
     * @Date 2018年1月5日 下午5:36:35 <br/>
     */
	@Override
	public int editForGuest(String roomOrderId, List<RoomOrderModel> roomOrdermodelList,String empId) {
		RoomOrderModel roomOrderModel = super.findById(roomOrderId);
		if(roomOrderModel == null){
			throw new BusinessException(RoomOrderReturnCodeEnum.ROOM_ORDER_QUERY_NO_FAILURE.getCode(),
					RoomOrderReturnCodeEnum.ROOM_ORDER_QUERY_NO_FAILURE.getDesc());
		}
		/**
		 * 非入住不能添加同来宾客
		 */
		if(roomOrderModel.getCheckinStatus() != RoomOrderStatusEnum.CHECKIN.getValue()){
			throw new BusinessException(RoomOrderReturnCodeEnum.ROOM_ORDER_OUT_CHAECKIN.getCode(),
					RoomOrderReturnCodeEnum.ROOM_ORDER_OUT_CHAECKIN.getDesc());
		}
		/**
		 * 删除掉原来的数据
		 */
		RoomOrderGuestModel roomOrderGuestModel = new RoomOrderGuestModel();
		roomOrderGuestModel.setRoomOrderId(roomOrderId);
		List<RoomOrderGuestModel> listRoomOrderGuest = roomOrderGuestService.list(roomOrderGuestModel);
		
		for(RoomOrderGuestModel item :listRoomOrderGuest){
			if(item.getRoomGuestId().equals(roomOrderModel.getMainGuestId())){
				continue;
			}
			if(roomOrderGuestService.del(item.getId()) == 0){
				throw new BusinessException(RoomOrderGuestReturnCodeEnum.ROOM_ORDER_GUEST_DEL_FAILURE.getCode(),
						RoomOrderGuestReturnCodeEnum.ROOM_ORDER_GUEST_DEL_FAILURE.getDesc());
			}
		}
		StringBuffer otherGuestName = new StringBuffer();
		/**
		 * 新增同来宾客
		 */
		for(RoomOrderModel item : roomOrdermodelList ){
			otherGuestName.append(item.getName()+",");
			RoomOrderGuestModel model = new RoomOrderGuestModel();
			model.setAccName(item.getName());
			model.setRemark(item.getRemark());
			model.setGroupId(roomOrderModel.getGroupId());
			model.setHotelId(roomOrderModel.getHotelId());
			model.setRoomGuestId(getGeustInfoId(item.getCertificateType(), item.getCertificateCode(), item.getName(),
					item.getMobile(), roomOrderModel.getGroupId(),roomOrderModel.getHotelId()));
			model.setRoomId(roomOrderModel.getRoomId());
			model.setRoomOrderId(roomOrderId);
			model.setBalance(new BigDecimal(0));
			if(roomOrderGuestService.save(model) == 0){
				throw new BusinessException(RoomOrderGuestReturnCodeEnum.ROOM_ORDER_GUEST_SAVE_FAILURE.getCode(),
						RoomOrderGuestReturnCodeEnum.ROOM_ORDER_GUEST_SAVE_FAILURE.getDesc());
			}
		}
		/**
		 * 更新订单的客人名称
		 */
		roomOrderModel.setOtherGuestName(otherGuestName.toString());
		roomOrderModel.setGmtCreate(new Date());
		roomOrderModel.setUpdateUserId(empId);
		return super.updateSelective(roomOrderModel);
	}
	/**
	 * 
	 * 功能:预离报表 <br/>
	 * 
	 * 重写：zhousc <br/>
	 * 
	 * @Date ：2018年1月10日 上午10:55:51<br/>
	 * 
	 * @param convert
	 * @return <br/>
	 * @see com.yuju.order.service.IRoomOrderService#dueOut(com.yuju.order.model.RoomOrderModel)
	 */
	@Override
	public List<RoomOrderModel> dueOut(RoomOrderModel model) {
		if(Utils.isNull(model.getCheckoutTime())){
			model.setCheckoutTime(new Date());
		}
		List<RoomOrderModel> list = roomOrderDao.dueOut(model);
		//根据订单号获取总消费和总应收
		for(int i = 0; i < list.size(); i++){
			Map<String, Object> detailByOrderId = accountService.getDetailByOrderId(list.get(i).getId());
			//总消费
			list.get(i).setTotalBill(detailByOrderId.get("ysSum"));
			//总收款
			list.get(i).setSettlementTotal(detailByOrderId.get("ssSum"));
		}
		
		return list;
	}
	/**
	 * 更新房管状态
	 * 功能: <br/>
	 * 
	 * 重写：xuehj <br/>
	 * 
	 * @Date ：2018年1月24日 下午6:17:34<br/>
	 * 
	 * @param id
	 * @param empId
	 * @return <br/>
	 * @see com.yuju.order.service.IRoomOrderService#updateRoomManageStatus(java.lang.String, java.lang.String)
	 */
	@Override
	public int updateRoomManageStatus(Byte roomManageStatus, List<RoomOrderModel> listRoomOrder, String empId) {
		for(RoomOrderModel item :listRoomOrder){
			RoomOrderModel model = new RoomOrderModel();
			RoomOrderModel find = super.findById(item.getId());
			model.setId(find.getId());
			model.setRoomManageInfo(item.getRoomManageInfo());
			model.setRoomManageStatus(roomManageStatus);
			model.setGmtModified(new Date());
			model.setUpdateUserId(empId);
			 if(super.updateSelective(model)==0){
				 throw new BusinessException(RoomOrderReturnCodeEnum.ROOM_ORDER_UPDATE_ROOM_FAILURE.getCode(),
						 RoomOrderReturnCodeEnum.ROOM_ORDER_UPDATE_ROOM_FAILURE.getDesc());
			 };
		}
		return 1;
	}
	/**
	 * 
	 * 功能:新预离报表 <br/>
	 * 
	 * sunyl
	 * @Date ：2018年1月10日 上午10:55:51<br/>
	 * 
	 * @param convert
	 * @return <br/>
	 * @see com.yuju.order.service.IRoomOrderService#dueOut(com.yuju.order.model.RoomOrderModel)
	 */
	@Override
	public Result freshDueOut(RoomOrderModel model) {
		Result result = new Result();
		if(model.getBusinessTime()==null){
			model.setBusinessTime(new Date());
		}
		model.setOrderByStr(" ord_room_order.room_code asc ");
		model.setNoCheckinStatus(RoomOrderStatusEnum.TEMPORARY.getValue());
		BigDecimal sumTotalForXF = new BigDecimal(0);
		BigDecimal sumTotalForBalance = new BigDecimal(0);
		List<RoomOrderModel> list = super.list(model);
		if(list != null && list.size()>0){
			//根据订单号获取总消费和总应收
			for(RoomOrderModel item:list){
				Map<String, Object> detailByOrderId = accountService.getDetailByOrderId(item.getId());
				if(detailByOrderId != null){
					//总消费
					item.setTotalBill(detailByOrderId.get("ysSum"));
					//总收款
					item.setSettlementTotal(detailByOrderId.get("ssSum"));
					sumTotalForBalance = sumTotalForBalance.add(item.getBalance());
					sumTotalForXF = sumTotalForXF.add(new BigDecimal(detailByOrderId.get("ysSum").toString()));
				}
			}
			Map<String,Object> data = new HashMap<>();
			data.put("sumTotalForBalance", sumTotalForBalance);
			data.put("sumTotalForXF", sumTotalForXF);
			result.setRows(list);
			result.setData(data);
			result.setStatus(ReturnStatusEnum.SUCCESS.getCode());
			result.setMsg(ReturnStatusEnum.SUCCESS.getDesc());
			result.setReturnCode(RoomOrderReturnCodeEnum.ROOM_ORDER_QUERY_SUCCESS.getCode());
			result.setReturnMsg(RoomOrderReturnCodeEnum.ROOM_ORDER_QUERY_SUCCESS.getDesc());
		}else{
			result.setStatus(ReturnStatusEnum.FAILURE.getCode());
			result.setMsg(ReturnStatusEnum.FAILURE.getDesc());
			result.setReturnCode(ReturnCodeEnum.NO_DATA.getCode());
			result.setReturnMsg(ReturnCodeEnum.NO_DATA.getDesc());
		}
		
		return result;
	}
}
